layui.use(['table', 'admin', 'ax','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;

    /**
     * Storage Location Management
     */
    var BasicPosition = {
        tableId: "basicPositionTable"
    };

    /**
     * 初始化表格的列
     */
    BasicPosition.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: 'ID'},
            {field: 'warehouseName', sort: true, title: 'Warehouse'},
            {field: 'warehouseNumber', sort: true, title: 'Warehouse Code'},
            {field: 'positionAreaName', sort: true, title: 'Warehouse Area'},
            {field: 'areaNumber', sort: true, title: 'Area Code'},
            {field: 'positionNumber', sort: true, title: 'Location Code', style:'color: #2b85e4;font-weight: 600;'},
            {field: 'positionType', sort: true, title: 'Location Type'},
            {field: 'positionCondition', sort: true, title: 'Storage Condition', hide: true},
            {field: 'traySize', sort: true, title: 'Tray Capacity', totalRow: true},
            {field: 'positionLength', sort: true, title: 'Length', hide: true},
            {field: 'positionWidth', sort: true, title: 'Width', hide: true},
            {field: 'positionHeight', sort: true, title: 'Height', hide: true},
            {field: 'positionPickingorder', sort: true, title: 'Picking Order'},
            {field: 'positionNotes', sort: true, title: 'Notes'},
            {field: 'createTime', sort: true, title: 'Creation Time'},
            {align: 'center', toolbar: '#tableBar', title: 'Actions'}
        ]];
    };

    /**
     * 点击查询按钮
     */
    BasicPosition.search = function () {
        var queryData = {};
        queryData['condition'] = $("#condition").val();
        queryData['WarehouseId'] = $("#warehouseId").val();
        queryData['positionAreaId'] = $("#positionAreaId").val();
        table.reload(BasicPosition.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });
    };
    
    // 导入
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: 'Storage Location Import',
            area: ['1000px', '750px'],
            anim: 5,
            content: Feng.ctxPath + '/basicPosition/toimportExcel',
            end: function () {
                table.reload(BasicPosition.tableId);
            }
        });
    });

    /**
     * 弹出添加对话框
     */
    BasicPosition.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/basicPosition/add';
    };
    
    /**
     * 导出excel按钮
     */
    BasicPosition.exportExcel = function () {
        var checkRows = table.checkStatus(BasicPosition.tableId);
        if (checkRows.data.length > 0) {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        } else {
            var queryData = {};
	        queryData['condition'] = $("#condition").val();
	        queryData['WarehouseId'] = $("#warehouseId").val();
	        queryData['positionAreaId'] = $("#positionAreaId").val();
            $.ajax({
                type: "POST",
                url: Feng.ctxPath + "/basicPosition/listAll",
                dataType:'json',
                data: queryData,
                beforeSend: function () {
                    //弹出加载中
                    index = layer.load(1, {
                        shade: [0.3, '#000'] //0.1透明度的白色背景
                    });
                },
                success: function (data) {
                    checkRows.data = data;
                    table.exportFile(tableResult.config.id, checkRows.data, 'xls');
                    layer.close(index);
                },
                error: function (data) {
                    console.log(data)
                }
            });
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    BasicPosition.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/basicPosition/edit?id=' + data.id;
    };

    /**
     * 点击删除
     *
     * @param data 点击按钮时候的行数据
     */
    BasicPosition.onDeleteItem = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/basicPosition/delete", function (data) {
                Feng.success("Deletion successful!");
                table.reload(BasicPosition.tableId);
            }, function (data) {
                Feng.error("Deletion failed!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("Are you sure you want to delete?", operation);
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + BasicPosition.tableId,
        url: Feng.ctxPath + '/basicPosition/list',
        page: true,
        limit: 60,
		limits:[60,120,240,360,480,1500,5000],
        height: "full-60",
        cellMinWidth: 100,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        totalRow: true ,//开启合计行
        defaultToolbar: ['filter', 'exports', 'print'],
        cols: BasicPosition.initColumn()
    });

    $('#btnPrint').click(function () {
    	var checkStatus = table.checkStatus('basicPositionTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
            	ids.push(data[i].positionNumber);
			}
	        layer.open({
	            type: 2,
	            title: 'Batch Print Location Codes',
	            area: ['900px', '550px'],
	            anim: 5,
	            content: Feng.ctxPath + '/basicPosition/tobtnqrCode?ids='+ids,
	            end: function () {
	            }
	        });
		} else {
			layer.alert('Please select at least one data record');
		}
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        BasicPosition.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        BasicPosition.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        BasicPosition.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + BasicPosition.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            BasicPosition.openEditDlg(data);
        } else if (layEvent === 'delete') {
            BasicPosition.onDeleteItem(data);
        }
    });
    
    //查询库区
    form.on('select(warehouseId)',function(){
    	$("#positionAreaId").empty();
    	$.ajax({
    		url:Feng.ctxPath + '/basicArea/queryArea',
    	    dataType:"json",   //返回格式为json
    	    async: false,
    	    data:{"areaWarehouseId":$("#warehouseId").val()},    //参数值
    	    type:"post",   //请求方式
    	    success:function(data){
    	        if(data.length>0){
    	        	var str = "<option value=''>Select Warehouse Area</option>";
    	        	$.each(data,function(key,value){
    	        		str += "<option value='"+value.id+"'>"+value.areaName+","+value.areaNumber+"</option>";
    	        	});
    	        	$("#positionAreaId").html(str);
    	        }
    	    }
    	});
        form.render('select');
    });
});
